package com.jblog.controller.directive.abs;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;

import com.jblog.common.web.freemarker.DirectiveUtils;
import com.jblog.common.web.freemarker.exception.ParamsRequiredException;
import com.jblog.core.model.blog.param.PostParam;
import com.jblog.core.model.common.Status;
import com.jblog.core.service.facde.BlogFacade;

import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;

public abstract class AbstractPreviousAndNextDirective implements
        TemplateDirectiveModel {
    
    @Autowired protected BlogFacade iblog; 

    public static final String PARAM_ID    = "id";
    public static final String PARAM_TYPE  = "type";
    

    protected Long id(Map<String, TemplateModel> params) throws TemplateException {
        return DirectiveUtils.getLong(PARAM_ID, params);
    }
    protected String type(Map<String, TemplateModel> params) throws TemplateException {
        return DirectiveUtils.getString(PARAM_TYPE, params);
    }
    
    private void checkParams(Map<String, TemplateModel> params) throws TemplateException {
        if (null == id(params) && null == type(params)) {
            throw new ParamsRequiredException(PARAM_ID + " or " + PARAM_TYPE);
        }
    }

    protected Object getData(Map<String, TemplateModel> params, Environment env)
            throws TemplateException {
        
        checkParams(params);
        
        Long id = id(params);
        String type = type(params);
        
        if (type.equalsIgnoreCase("POST")) {
            PostParam postParam = new PostParam(id);
            postParam.setStatus(Status.NORMAL);
            return iblog.findPreviousAndNextOfPost(postParam);
        } else {
            return null;
        }
    }
}
